package com.sita.palla.web.config;


import org.springframework.core.annotation.Order;
import org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.filter.HiddenHttpMethodFilter;
import org.springframework.web.filter.RequestContextFilter;
import org.springframework.web.filter.ServletContextRequestLoggingFilter;
import org.springframework.web.multipart.support.MultipartFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

import javax.servlet.Filter;
import javax.servlet.MultipartConfigElement;
import javax.servlet.ServletRegistration;
import java.nio.charset.StandardCharsets;

/**
 * Created by xiaodong on 15/12/7.
 */
@Order(2)
public class ServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class<?>[]{WebConfiguration.class};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[0];
    }

    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }

    @Override
    protected Filter[] getServletFilters() {
        CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
        characterEncodingFilter.setEncoding(StandardCharsets.UTF_8.displayName());
        characterEncodingFilter.setForceEncoding(true);

        OpenEntityManagerInViewFilter emf1 = new OpenEntityManagerInViewFilter();
        emf1.setPersistenceUnitName("backendPU");
        emf1.setEntityManagerFactoryBeanName("backendEntityManagerFactory");
//        OpenEntityManagerInViewFilter emf2 = new OpenEntityManagerInViewFilter();
//        emf2.setPersistenceUnitName("OraUnit");
//        emf2.setEntityManagerFactoryBeanName("oraEntityManagerFactory");


        return new Filter[]{characterEncodingFilter, new MultipartFilter(),
                emf1, //emf2,
                new HiddenHttpMethodFilter(), new ServletContextRequestLoggingFilter(), new RequestContextFilter()};
    }

    @Override
    protected void customizeRegistration(ServletRegistration.Dynamic registration) {
        MultipartConfigElement multipartConfigElement = new MultipartConfigElement(
                "",1000000,1000000,1000000);
              //  Constants.getAvatarDir(), Constants.getMaxFileSize(),
             //   Constants.getMaxRequestSize(), Constants.getFileSizeThreshold());
        registration.setMultipartConfig(multipartConfigElement);
    }


}
